<template>
  <div>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell v-for="item in list" :key="item.art_id" :title="item.title"/>
    </van-list>
  </div>
</template>

<script>
import { getSearchResults } from '@/api/search'

export default {
  name: 'Search-results',
  props: {
    // 输入框的值
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      error: false
    }
  },
  methods: {
    async onLoad () {
      try {
        const res = await getSearchResults({
          page: this.page,
          per_page: 10,
          q: this.searchText
        })
        if (Math.random() > 0.5) {
          console.lo(1)
        }
        this.page++
        this.list.push(...res.results)
        this.loading = false
        if (this.list.length >= res.total_count) {
          this.finished = true
        }
      } catch (e) {
        this.loading = false
        this.error = true
      }

      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      /*      setTimeout(() => {
          for (let i = 0; i < 10; i++) {
            this.list.push(this.list.length + 1)
          }

          // 加载状态结束
          this.loading = false

          // 数据全部加载完成
          if (this.list.length >= 40) {
            this.finished = true
          }
        }, 1000) */
    }
  }
}
</script>

<style scoped lang='less'>

</style>
